<template>
  <!--  jiera-->
  <div class='comment_container'>
    <div class='input_container'>
      <div class='info_search'>
        <div class='count'>{{ data.total || 0 }}个评论</div>
        <!--            <div class="search">-->
        <!--                <ElButton-->
        <!--                  v-for="item in searchType"-->
        <!--                  :key="item.value"-->
        <!--                  @click.stop="searchKey = item.value"-->
        <!--                  :type="searchKey === item.value ? 'primary' : ''"-->
        <!--                >{{ item.label }}</ElButton>-->
        <!--            </div>-->
      </div>
      <div class='welcome_to_comment'>
        <el-avatar :src='props.userAvatar' @click.stop='handleGoPersonalHomePage' />
        <MyTextarea v-model='commentContent' style='flex:1'>
          <el-button type='primary' round @click='handleAddComment' style='padding: 0 30px'
          >发布
          </el-button>
        </MyTextarea>
      </div>
    </div>
    <div
      v-for='item in commentList'
      :key='item.id'
      class='comment_list_container mb-3 cursor-pointer'
    >
      <div class='flex gap-3 items-center'>
        <el-avatar :src='item.userAvatar' />
        <div class='text-sm font-semibold' style='color: #2F2F2F'>
          <div>{{ item.createdName }}</div>
        </div>
        <div class='text-xs'></div>
        <div style='font-size: 20px; font-weight: bold; color: #6C74B3; text-shadow: 2px 2px 4px #aaa;'>vip</div>
        <div style='color: #989694'>{{ dayjs(item.createdTime).format('YYYY-MM-DD HH:MM:ss') }}</div>
      </div>
      <div class='mt-2'>
        {{ item.content }}
      </div>
      <!-- 评论 下面内容好像没啥用-->
      <div v-if='!!item.taskCommentVO'>
        <div>{{ item.taskCommentVO.content }}</div>
      </div>
      <div class='hah' style='width: 27%; justify-content: flex-end;'>
        <img v-if='item.images && item.images.length > 0'
             :src='item.images[0]'
             alt=''
             class='image-display'
             @click.stop='showFullSizeImage(item.images[0])'
        />
      </div>
      <!-- 用于展示全屏大图的模态框 -->
      <div class='image-modal' v-if='isFullSizeImageVisible'>
        <img :src='fullSizeImageSrc' alt='' @click.stop='hideFullSizeImage' />
      </div>

      <div class='mt-4 flex items-center gap-8'>
        <div
          class='flex items-stretch gap-0.5 cursor-pointer text-sm'
          hover:text-gray-400
          v-for='handle in handleList'
          :key='handle.icon'
          @click.stop='handleClick(handle.type, item.id!)'
        >
          <div
            v-if='handle.checkedFieldName&&item[handle.checkedFieldName]'
            :class='handle.checkedIcon'
            :style="{ color: '#409eff' }"
          ></div>
          <div v-else :class='handle.icon'></div>
          <div>{{ item[handle.fieldName] || 0 }}</div>
        </div>
        <button @click.stop='handleDeleteComment(item.id)' class='delete-btn'>
          &times; <span class='small-text'>删除</span>
        </button>
      </div>
    </div>
  </div>
  <!--  分页-->
  <div>
    <div class='mt-2 flex justify-end'>
      <el-pagination
        background
        layout='total,prev, pager, next'
        :total='data.total'
        @current-change='currentPages'
      />
    </div>
  </div>
</template>

<script lang='ts' setup>
import dayjs from 'dayjs'
import MyTextarea from '@/components/MyTextarea/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ref } from 'vue'
// import { Pagination } from '~/composables/api/task'
const props = withDefaults(
  defineProps<{
    data: {
      list: Array<any>,
      total: number
    },
    taskId: number | string
    pagination: Pagination
    userAvatar: string
    commentType: number
    receiverList: Array<any>
  }>(),
  {
    data: () => ({ list: [], total: 0 }),
    taskId: 0,
    pagination: () => ({ pageSize: 10, pageNum: 1, total: 0 }),
    userAvatar: localStorage.getItem('userAvatar'),
    receiverList: () => [],
  },
)

const $emit = defineEmits(['refresh'])

// 处理事件列表
const handleList = ref([
  {
    icon: 'i-carbon-thumbs-up',
    checkedIcon: 'i-carbon-thumbs-up-filled',
    type: 'liked',
    fieldName: 'likedNum',
    checkedFieldName: 'isLiked',
  },
  // {
  //   icon: 'i-carbon-ibm-watson-assistant',
  //   type: 'comment',
  //   fieldName: 'commentNum',
  // },
])

const commentList: ComputedRef<any[]> = computed(() => {
  return props.data.list
})

const handleClick = async (type: string, id: string | number) => {
  if (type === 'liked') {
    await service.comment.likeComment(id)
    $emit('refresh')
  }
}


const searchKey = ref(0)
const searchType = [
  {
    label: '最热',
    value: 0,
  },
  {
    label: '最新',
    value: 1,
  },
]

const commentContent = ref({
  content: '',
  images: [],
})

// 评论的发布按钮
const handleAddComment = async () => {
  const data = {
    taskId: Number(props.taskId),
    content: commentContent.value.content,
    images: commentContent.value.images,
    type: props.commentType,
  }
  // 完成情况发评论需校验当前登录人是否是任务领取人
  if (data.type === 1) {
    // 遍历receiverList集合进行判断
    let isReceiver = false
    for (const receiver of props.receiverList) {
      if (receiver.receiverName !== undefined && receiver.receiverName === userStore.userInfo.name) {
        isReceiver = true
        break
      }
    }
    if (isReceiver) {
      if (data.content.trim() !== '') {
        commentContent.value.content = ''
        await service.comment.add(data)
        $emit('refresh')
      } else {
        ElMessage.warning('输入内容不为空~')
      }
    } else {
      ElMessage.warning('只有任务领取人才可发布完成情况！')
    }
  } else if (data.type === 0) {
    if (data.content.trim() !== '') {
      commentContent.value.content = ''
      await service.comment.add(data)
      $emit('refresh')
    } else {
      ElMessage.warning('输入内容不为空~')
    }
  } else {

  }
}

const currentPages = (pageNum) => {
  const queryData = {
    taskId: Number(props.taskId),
    pageSize: props.pagination.pageSize,
    pageNum: pageNum,
  }
  service.comment.list(queryData).then((res) => {
    props.data.list = res.list
    props.pagination.pageNum = pageNum
    $emit('refresh')
  })
}

const currentPage = computed({
  get: () => props.pagination.pageNum,
  set: (value) => {
    $emit('refresh', { pageNum: value })
  },
})

const handleDeleteComment = async (id: any) => {
  const confirmResult = await ElMessageBox.confirm('确认删除该评论?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })

  if (confirmResult) {
    const data = { taskCommentId: id }
    await service.comment.delete(data)
    $emit('refresh')
  }
}
const router = useRouter()
const userStore = useUserStore()

const handleGoPersonalHomePage = () => {
  router.push(`/main/personalHomepage?id=${userStore.userInfo.uid}`)
}

const commentInfo = ref<any>({})

// 存储是否显示全屏大图的状态
const isFullSizeImageVisible = ref(false)
// 存储当前要展示的全屏大图的源地址
const fullSizeImageSrc = ref('')
// 存储当前图片在图片列表中的索引
const currentIndex = ref(0)

// 图片点击显示全屏
const showFullSizeImage = (image) => {
  isFullSizeImageVisible.value = true
  fullSizeImageSrc.value = image
  currentIndex.value = commentInfo.images.indexOf(image)
}

const hideFullSizeImage = () => {
  isFullSizeImageVisible.value = false
}


</script>
<style scoped lang='scss'>
.comment_container {
  .input_container {
    .info_search {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .welcome_to_comment {
      display: flex;
      gap: 20px;
      padding: 10px;
      margin-top: 10px;

      .comment_container {
        display: flex;
        flex: 1;
        align-items: center;
        justify-content: center;
        border-radius: 5px;
        box-shadow: 0 0 2px 2px rgba(0, 0, 0, 10%);

        .comment_input {
          width: 95%;
          height: 80%;
          padding: 10px;
          background-color: rgba(0, 0, 0, 10%);
          border-radius: 5px;

          &:focus-visible {
            outline: none;
          }
        }
      }
    }
  }
}

.small-text {
  font-size: 0.85em; /* 根据需要调整字体大小，这里设置为比原来小的 0.7 倍 */
}
</style>


